<template>
  <div class="main">
<!--    1.大用户表 2.户表-->
    <el-tabs v-model="warnTargetType" @tab-click="handleTabClick" class="type_tab">
      <el-tab-pane label="户表用量区间设置" name="2">
        <div class="box mb20">
          <el-row class="box-title">
            <el-col :span="20">基础设置</el-col>
            <el-col :span="4" style="text-align: right">
              <el-button
                size="mini"
                type="primary"
                @click="alterStrategy"
              >
                批量修改报警策略
              </el-button>
            </el-col>
          </el-row>
          <div class="box-form pt20">
            <el-form>
              <el-form-item label="所属客户" label-width="100px">
                <el-select filterable v-model="tenantId"
                           placeholder="请选择所属客户" @change="tenantIdChange">
                  <el-option
                    v-for="dept in deptOption"
                    :key="dept.tenantId"
                    :label="dept.deptName"
                    :value="dept.tenantId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="box mb20">
          <el-row class="box-title">
            <el-col :span="20">户表报警设置
              <el-tooltip content="双击tab标签名称可修改策略名称" placement="top">
                <i class="el-icon-s-opportunity" style="margin-left: 10px;color: #c2c775"></i>
              </el-tooltip>
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button
                size="mini"
                type="primary"
                @click="addTab"
              >
                新增报警策略
              </el-button>
            </el-col>
          </el-row>
          <div class="box-form">
            <el-tabs v-model="editableTabsValueXb" type="card" closable @tab-remove="removeTab">
              <el-tab-pane
                v-for="(strategyItem, strategyIndex) in editableTabsXb"
                :key="strategyItem.name"
                :label="strategyItem.title"
                :name="strategyItem.name"
              >
                <template slot="label">
                    <span v-if="!strategyItem.inputFlag" style="display: inline-block;text-align: center;"
                          @dblclick="tabsContent(strategyItem)">
                      {{ strategyItem.title }}
                    </span>
                  <el-input size="mini" v-else-if="!!strategyItem.inputFlag" :ref="`myInput${strategyItem.name}`"
                            v-model="strategyItem.title" type="text" class="tabsInput"
                            @blur="inputBlur(strategyItem)"/>
                </template>
                <template>
                  <el-form :ref="'formXbRef' + strategyIndex" :model="strategyItem.form">
                    <el-form-item
                      label-width="230px"
                      v-for="(fieldItem, fieldIndex) in strategyItem.form.fields"
                      :key="fieldIndex"
                      :label="fieldItem.label"
                      :prop="'fields.' + fieldIndex + '.value'"
                      v-show="fieldItem.label !== '所属客户' && fieldItem.label !== 'strategy'"
                      :rules="fieldItem.rules"
                    >
                      <el-input-number style="width: 30%" :disabled="(strategyItem.title==='通用' && systemFlag !== 0)" v-model="fieldItem.value" v-show="fieldItem.label === '户表持续零用量' || fieldItem.label === '户表持续未上报'"></el-input-number>
                      <el-input-number style="width: 30%" :disabled="(strategyItem.title==='通用' && systemFlag !== 0)" v-model="fieldItem.value" :precision="3" :step="0.001" v-show="fieldItem.label === '户表用量突增'"></el-input-number>
<!--                      如果备注不为空，则改表单参数为报警类型参数-->
                      <el-tooltip :content="'是否启用' + fieldItem.label" placement="top">
                        <el-switch :disabled="(strategyItem.title==='通用' && systemFlag !== 0)" v-if="fieldItem.remark != null" v-model="fieldItem.enabled" class="ml10"></el-switch>
                      </el-tooltip>
                      <span>{{ fieldItem.remark }}</span>
                    </el-form-item>
                  </el-form>
                </template>
                <div style="text-align: center;">
                  <el-button type="danger" v-show="!strategyItem.isNew"
                             @click="handleDelete('2', strategyItem.title, strategyItem.form)" v-has-permi="['basedata:usage_range:remove']">
                    删除策略
                  </el-button>
                  <el-button type="primary" v-show="!strategyItem.newStrategy" style="margin-left: 30px"
                             @click="onSubmit(strategyItem.title, false, strategyIndex, strategyItem.form)" v-has-permi="['basedata:usage_range:add']">
                    保存设置
                  </el-button>
                  <el-button type="primary" v-show="strategyItem.newStrategy" style="margin-left: 30px"
                             @click="onSubmit(strategyItem.title, true, strategyIndex, strategyItem.form)" v-has-permi="['basedata:usage_range:add']">
                    创建策略
                  </el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="大用户表用量区间设置" name="1">
        <div class="box mb20">
          <el-row class="box-title">
            <el-col :span="20">基础设置</el-col>
            <el-col :span="4" style="text-align: right">
              <el-button
                size="mini"
                type="primary"
                @click="alterStrategy"
              >
                批量修改报警策略
              </el-button>
            </el-col>
          </el-row>
          <div class="box-form pt20">
            <el-form>
              <el-form-item label="所属客户" label-width="100px">
                <el-select clearable filterable v-model="tenantId"
                           placeholder="请选择所属客户" @change="tenantIdChange">
                  <el-option
                    v-for="dept in deptOption"
                    :key="dept.tenantId"
                    :label="dept.deptName"
                    :value="dept.tenantId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="box mb20">
          <el-row class="box-title">
            <el-col :span="20">
              <span>大用户表报警设置</span>
<!--              <span style="color: #efefef;font-size: 14px;padding-left: 10px;">双击tab标签名称可修改策略名称</span>-->
              <el-tooltip content="双击tab标签名称可修改策略名称" placement="top">
                <i class="el-icon-s-opportunity" style="margin-left: 10px;color: #c2c775"></i>
              </el-tooltip>
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button
                size="mini"
                type="primary"
                @click="addTab"
              >
                新增报警策略
              </el-button>
            </el-col>
          </el-row>
          <div class="box-form">
            <el-col :span="24">
              <el-tabs v-model="editableTabsValueDb" type="card" closable @tab-remove="removeTab">
                <el-tab-pane
                  v-for="(strategyItem, strategyIndex) in editableTabsDb"
                  :key="strategyItem.name"
                  :label="strategyItem.title"
                  :name="strategyItem.name"
                >
                  <template slot="label">
                    <span v-if="!strategyItem.inputFlag" style="display: inline-block;text-align: center;"
                          @dblclick="tabsContent(strategyItem)">
                      {{ strategyItem.title }}
                    </span>
                    <el-input size="mini" v-else-if="!!strategyItem.inputFlag" :ref="`myInput${strategyItem.name}`"
                              v-model="strategyItem.title" type="text" class="tabsInput"
                              @blur="inputBlur(strategyItem)"/>
                  </template>
                  <template>
                    <el-form :ref="'formDbRef' + strategyIndex" :model="strategyItem.form">
                      <el-form-item
                        label-width="230px"
                        v-for="(fieldItem, fieldIndex) in strategyItem.form.fields"
                        :key="fieldIndex"
                        :label="fieldItem.label"
                        :prop="'fields.' + fieldIndex + '.value'"
                        v-show="fieldItem.label !== '所属客户' && fieldItem.label !== 'strategy'"
                        :rules="fieldItem.rules"
                      >
                        <el-time-picker
                          is-range
                          format="HH:mm:ss"
                          value-format="HH:mm:ss"
                          v-if="fieldItem.label === '夜间小流时间段'"
                          style="width: 30%"
                          v-model="fieldItem.value"
                          :disabled="(strategyItem.title==='通用' && systemFlag !== 0)"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间">
                        </el-time-picker>
                        <el-input-number style="width: 30%" :disabled="(strategyItem.title==='通用' && systemFlag !== 0)" v-model="fieldItem.value" v-show="fieldItem.label === '大用户表数据完整性' || fieldItem.label === '大用户表通讯故障' || fieldItem.label === '大用户表流量空值报警'"></el-input-number>
                        <el-input-number style="width: 30%" :disabled="(strategyItem.title==='通用' && systemFlag !== 0)" v-model="fieldItem.value" :precision="3" :step="0.001" v-show="fieldItem.label === '大用户表压力数值突变' || fieldItem.label === '大用户表日用量预警' || fieldItem.label === '大用户表通讯板电压异常' || fieldItem.label === '大用户表累计流量突减报警阈值' || fieldItem.label === '大用户表瞬时流量数值突变'"></el-input-number>
                        <el-tooltip :content="'是否启用' + fieldItem.label" placement="top">
                          <el-switch :disabled="(strategyItem.title==='通用' && systemFlag !== 0)" v-show="fieldItem.remark != null" v-model="fieldItem.enabled" class="ml10"></el-switch>
                        </el-tooltip>
                        <span>{{ fieldItem.remark }}</span>
                      </el-form-item>
                    </el-form>
                  </template>
                  <div style="text-align: center;">
                    <el-button type="danger" v-show="!strategyItem.isNew"
                               @click="handleDelete('1', strategyItem.title, strategyItem.form)" v-has-permi="['basedata:usage_range:remove']">
                      删除策略
                    </el-button>
                    <el-button type="primary" v-show="!strategyItem.newStrategy" style="margin-left: 30px"
                               @click="onSubmit(strategyItem.title, false, strategyIndex, strategyItem.form)" v-has-permi="['basedata:usage_range:add']">保存设置
                    </el-button>
                    <el-button type="primary" v-show="strategyItem.newStrategy" style="margin-left: 30px"
                               @click="onSubmit(strategyItem.title, true, strategyIndex, strategyItem.form)" v-has-permi="['basedata:usage_range:add']">
                      创建策略
                    </el-button>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </div>
        </div>

      </el-tab-pane>
    </el-tabs>
<!--    策略名称输入对话框-->
    <el-dialog title="策略名称" :visible.sync="open" width="300px">
      <el-form :model="form" ref="formRef" :rules="rules" size="mini" label-width="90px">
        <el-form-item label="策略名称" prop="strategy">
          <el-input v-model="form.strategy" placeholder="请输入策略名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onStrategyCancel">取 消</el-button>
        <el-button type="primary" @click="onStrategySubmit">确 定</el-button>
      </div>
    </el-dialog>

<!--    批量修改户表报警策略弹窗-->
    <el-dialog :title="title" :visible.sync="openStrategy" :width="isSelectAll ? '55%' : '75%'" append-to-body @close="closeStrategyModal" style="min-height: 200px;">
      <el-row>
        <el-col :span="22">
          <el-form label-width="120px" :model="queryParams" ref="queryFormRef" :rules="rules" size="mini" :inline="true">
            <el-form-item label="客户名称" prop="tenantId" :rules="[{required: isSelectAll ? true : false, message:'请选择客户', trigger: 'change'}]">
              <el-select filterable v-model="queryParams.tenantId" @change="handleTenantIdChange"
                         placeholder="请选择所属客户">
                <el-option
                  v-for="dept in deptOption"
                  :key="dept.tenantId"
                  :label="dept.deptName"
                  :value="dept.tenantId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :rules="[{required: isSelectAll ? true : false, message:'请选择报警策略', trigger: 'change'}]" :label="isSelectAll ? '设置报警策略' : '报警策略筛选'" prop="strategy">
              <el-select filterable v-model="queryParams.strategy"
                         placeholder="请选择报警策略" clearable>
                <el-option
                  v-for="dept in strategyList"
                  :key="dept.value"
                  :label="dept.label"
                  :value="dept.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备编号筛选" prop="terminalId" v-show="!isSelectAll">
              <el-input placeholder="请输入设备编号查询" v-model="queryParams.terminalId"></el-input>
            </el-form-item>
            <el-form-item label="是否全选">
              <el-radio-group v-model="isSelectAll" v-removeAriaHidden @change="isSelectAllChange">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2" v-show="!isSelectAll">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-col>
      </el-row>
      <el-row v-if="!isSelectAll" style="display: flex;justify-content: center;align-items: center;">
        <el-transfer
          v-loading="loading"
          style="margin: 20px auto;"
          v-model="terminalsValue"
          :data="terminalsList"
          :titles="['设备信息', '待改设备']"
          :props="defaultProps"
          :render-content="renderContent"
          @right-check-change="rightCheckChange"
          @change="handleTransferChange"
          :right-default-checked="rightDefaultChecked">
<!--          <pagination-->
<!--            small-->
<!--            slot="left-footer"-->
<!--            v-show="total>0 && this.warnTargetType === '2'"-->
<!--            :total="total"-->
<!--            :page.sync="queryParams.pageNum"-->
<!--            :limit.sync="queryParams.pageSize"-->
<!--            @pagination="confirmRefreshData"-->
<!--          />-->
          <pagination
            small
            slot="left-footer"
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="confirmRefreshData"
          />
          <div slot="right-footer">
            <el-form size="mini" ref="newStrategyFormRef" :model="newStrategyForm" :rules="newStrategyFormRules" :inline="true" label-width="150px">
              <el-form-item label="报警策略设置为" prop="strategy">
                <el-select filterable v-model="newStrategyForm.strategy" clearable
                           placeholder="请选择报警策略">
                  <el-option
                    v-for="dept in strategyList"
                    :key="dept.value"
                    :label="dept.label"
                    :value="dept.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-transfer>
      </el-row>
      <!--        底部操作按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onOk">确定修改</el-button>
        <el-button @click="closeStrategyModal">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listTerminalsDb } from "@/api/record/terminalsdb";
import { listTerminalxb } from "@/api/record/terminalxb";
import { getDicts } from '@/api/system/dict/data.js'
import { deptList } from '@/api/system/dept.js'
import { usageRange, getUsageRange, deleteUsageRange, editStrategyBatchXb, editStrategyBatchDb } from '@/api/basedata/dosageInterval.js'

export default {
  name: 'DosageInterval',
  data() {
    var validateNoSpace = (rule,value,callback) => {
      if(value.trim() === ''){
        callback(new Error('输入项不能为空格'))
      }else if(value === '通用') {
        callback(new Error('名称不能为通用'))
      }else{
        callback();
      }
    }
    return {
      screenHeight: 0,
      tabContentHeight: '',
      loading: false,
      // 切换分页影响提示是否显示
      // 右侧选中的数组
      rightDefaultChecked: [],
      // 某个用户下的报警策略列表
      strategyList: [],
      // 选中的设备id数组
      // ids: [],
      defaultProps: {
        label: 'locationNb',
        key: 'id',
        disabled: false,
      },
      // 新报警策略表单
      newStrategyForm: {
        strategy: null,
      },
      nextPage: null,
      // 表档案查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        terminalId: null,
        loginUserId: null,
        systemFlag: null,
        tenantId: null,
        strategy: null,
        orderByColumn: 'createTime',
        isAsc: 'descending'
      },
      isSelectAll: null,
      // 表档案总数
      total: 0,
      // 表档案数据
      terminalsList: [],
      // 选中的表档案
      terminalsValue:[],
      // 弹窗的名字
      title: '',
      // 批量修改户表\大用户表报警策略弹窗
      openStrategy: false,
      // 弹窗状态
      open: false,
      // 策略弹框表单
      form: {},
      // 修改
      oldStrategy: null,
      // 设备类型
      warnTargetType: '2',
      // 表单
      formXb: {
        fields: []
      },
      formDb: {
        // fields1: [],
        fields: []
      },
      // 参数
      paramsXb: {},
      paramsDb: {},
      // 夜间小流开始时间
      nightFlowBeginTime: null,
      // 夜间小流结束时间
      nightFlowEndTime: null,
      // 所属客户
      tenantId: null,
      // 客户选择下拉
      deptOption: [],
      // 获取报警类型
      alarmTypeList: [],
      // 当前的tab
      editableTabsValueDb: '',
      editableTabsDb: [],
      // 户表报警策略tab
      editableTabsValueXb: '',
      editableTabsXb: [],
      // 大用户表数据
      dataDb: [],
      dataXb: [],
      // 表单校验
      rules: {
        strategy: [{ required: true, message: '策略名称不能为空', trigger: 'blur'},{validator: validateNoSpace, trigger: 'blur'}]
      },
      newStrategyFormRules: {
        strategy: [{ required: true, message: '报警策略不能为空', trigger: 'change'}]
      }
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    systemFlag() {
      return this.$store.state.user.systemFlag
    },
    _tenantId() {
      return this.$store.state.user.tenantId
    },
    loginUserId() {
      return this.$store.state.user.userId
    },
    getAvailableHeight() {
      return (this.screenHeight - 100) + 'px'
    },
  },
  watch: {
    'queryParams.tenantId'(val){
      // this.clearValidate()
      if(this.$refs.newStrategyFormRef) {
        this.$nextTick(() => {
          this.$refs.newStrategyFormRef.clearValidate();
        });
      }
      if(!this.isSelectAll){
        this.newStrategyForm = {
          strategy: null,
        }
      }
    }
  },
  mounted() {
    if(this.systemFlag === 0) {
      this.tenantId = '0'
    }else {
      this.tenantId = this._tenantId
    }
    this.getDeptList()
    this.getAlarmType()
  },
  methods: {
    // 右侧列表元素被用户选中 / 取消选中时触发
    rightCheckChange(e){
      // this.ids = e
    },
    // 重置查询
    resetQuery(){
      this.clearValidate()
      this.queryParams = {
        pageNum: 1,
        pageSize: 50,
        terminalId: null,
        loginUserId: this.loginUserId,
        systemFlag: this.systemFlag,
        tenantId:  this.queryParams.tenantId,
        strategy: null,
        orderByColumn: 'createTime',
        isAsc: 'descending'
      }
    },
    // 查询户表、大用户表数据
    handleQuery(){
      this.queryParams.pageNum = 1
      switch (this.warnTargetType){
        case '1':
          this.confirmRefreshData()
          break;
        case '2':
          this.confirmRefreshData()
          break;
      }
    },
    // 自定义渲染穿梭框数据
    renderContent(h, option) {
      return <span>设备编号：{ option.terminalId} - 策略名称：{ option.strategyName }</span>
    },
    // 监听是否全选单选按钮
    async isSelectAllChange(e) {
      if((!e && this.warnTargetType === '2' ) || (!e && this.warnTargetType === '1')){
        this.resetQuery()
        await this.confirmRefreshData()
      }else if((e && this.warnTargetType === '2') || (e && this.warnTargetType === '1')){
        this.resetQuery()
      }
    },
    // 判断请求数据的时候是否加提示确认
    confirmRefreshData(){
      if(this.warnTargetType === '1'&& this.terminalsValue.length > 0){
        this.$confirm('该操作会导致右侧待修改设备列表被重置，确定进行吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.terminalsValue = []
          this.getListDb()
        }).catch(() => {
        });
      }else if(this.warnTargetType === '1'){
        this.getListDb()
      }else if(this.warnTargetType === '2' && this.terminalsValue.length > 0){
        this.$confirm('该操作会导致右侧待修改设备列表被重置，确定进行吗！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.terminalsValue = []
          this.getListXb()
        }).catch(() => {
        });
      }else if(this.warnTargetType === '2'){
        this.getListXb()
      }
    },
    // 获取户表档案数据
    getListXb() {
      this.loading = true
      this.queryParams.systemFlag = this.systemFlag
      this.queryParams.loginUserId = this.loginUserId
      listTerminalxb(this.queryParams).then(response => {
        this.terminalsList = response.rows;
        this.total = response.total;
        this.loading = false
      });
    },
    // 获取大用户表档案数据
    getListDb() {
      this.loading = true
      this.queryParams.systemFlag = this.systemFlag
      this.queryParams.loginUserId = this.loginUserId
      listTerminalsDb(this.queryParams).then(response => {
        this.terminalsList = response.rows;
        this.total = response.total
        this.loading = false
      });
    },
    // 穿梭框改变事件
    handleTransferChange(currentData, position, value) {
      this.terminalsValue = currentData
    },
    // 确认批量修改报警策略
    onOk() {
      let params = {}
      this.$refs.queryFormRef.validate(valid => {
        if(valid){
          // 批量修改大用户表报警策略
          if(this.warnTargetType === '1' && this.isSelectAll) {
            params = {
              tenantId: this.queryParams.tenantId,
              strategy: this.queryParams.strategy
            }
            editStrategyBatchDb(params).then(response => {
              if(response.code === 200){
                this.$message.success(response.msg)
                this.openStrategy = false
              }else {
                this.$message.error(response.msg)
              }
            })
          }else if(this.warnTargetType === '1' && !this.isSelectAll){
            if(this.terminalsValue.length === 0){
              return this.$message.warning('请选择需要修改的设备!')
            }
            this.$refs.newStrategyFormRef.validate(valid => {
              if(valid){
                params = {
                  ids: this.terminalsValue,
                  strategy: this.newStrategyForm.strategy
                }
                editStrategyBatchDb(params).then(response => {
                  if(response.code === 200){
                    this.$message.success(response.msg)
                    this.terminalsValue = []
                    this.confirmRefreshData()
                  }else {
                    this.$message.error(response.msg)
                  }
                })
              }
            })
          } else if(this.warnTargetType === '2' && this.isSelectAll) {
            params = {
              tenantId: this.queryParams.tenantId,
              strategy: this.queryParams.strategy
            }
            editStrategyBatchXb(params).then(response => {
              if(response.code === 200){
                this.$message.success(response.msg)
                this.openStrategy = false
              }else {
                this.$message.error(response.msg)
              }
            })
          }else if(this.warnTargetType === '2' && !this.isSelectAll) {
            if(this.terminalsValue.length === 0){
              return this.$message.warning('请选择需要修改的设备!')
            }
            this.$refs.newStrategyFormRef.validate(valid => {
              if(valid){
                params = {
                  ids: this.terminalsValue,
                  strategy: this.newStrategyForm.strategy
                }
                editStrategyBatchXb(params).then(response => {
                  if(response.code === 200){
                    this.$message.success(response.msg)
                    this.terminalsValue = []
                    this.confirmRefreshData()
                  }else {
                    this.$message.error(response.msg)
                  }
                })
              }
            })
          }
        }
      })
    },
    // 关闭批量修改户表、大用户表报警策略弹窗
    closeStrategyModal() {
      this.openStrategy = false
    },
    // 批量修改户表、大用户表报警策略
    alterStrategy(){
      this.getStrategyList(this._tenantId)
      // this.queryParams.tenantId = this._tenantId
      // queryParams: {
      //   pageNum: 1,
      //     pageSize: 50,
      //     terminalId: null,
      //     loginUserId: null,
      //     systemFlag: null,
      //     tenantId: null,
      //     strategy: null,
      //     orderByColumn: 'createTime',
      //     isAsc: 'descending'
      // },
      this.resetQuery()
      this.isSelectAll = true
      this.terminalsValue = []
      this.newStrategyForm = {
        strategy: null,
      }
      this.queryParams.tenantId = this._tenantId
      if(this.warnTargetType === '2'){
        this.title = '批量修改户表报警策略'
      }else{
        this.title = '批量修改大用户表报警策略'
      }
      this.openStrategy = true
    },
    // 清除策略名称表单验证
    clearValidate() {
      if (this.$refs.formRef) {
        this.$nextTick(() => {
          this.$refs.formRef.clearValidate();
        });
      }else if(this.$refs.queryFormRef){
        this.$nextTick(() => {
          this.$refs.queryFormRef.clearValidate();
        });
      }else if(this.$refs.newStrategyFormRef){
        this.$nextTick(() => {
          this.$refs.newStrategyFormRef.clearValidate();
        });
      }
    },
    // 双击tab的标签名称，展示输入框
    tabsContent(val) {
      if(val.title === '通用'){
        val.inputFlag = false
        this.$message.warning('通用策略名称不可修改！')
      }else{
        this.oldStrategy = val.title
        val.inputFlag = true
      }
    },
    // tab名称失焦后关闭输入框
    inputBlur(val) {
      let count = 0
      if(val.title === '通用'){
        val.title = this.oldStrategy
        return this.$message.warning('名称不可以为通用')
      }else if(val.title === ''){
        val.title = this.oldStrategy
        return this.$message.warning('名称不可以为空')
      }else if(this.warnTargetType === '1'){
        this.editableTabsDb.forEach(item => {
          if(val.title === item.title){
            count++
            if(count > 1){
              val.title = this.oldStrategy
              return this.$message.warning('该策略名称已存在,请更换')
            }
          }
        })
        val.inputFlag = true
      }else if(this.warnTargetType === '2') {
        this.editableTabsXb.forEach(item => {
          if(val.title === item.title){
            count++
            if(count > 1){
              val.title = this.oldStrategy
              return this.$message.warning('该策略名称已存在,请更换')
            }
          }
        })
      }
      val.inputFlag = false
    },
    // 策略名称确认
    onStrategySubmit(){
      // 判断名称是否已经存在，存在为true
      let _flag = false
      this.$refs.formRef.validate(valid => {
        if(valid){
          if(this.warnTargetType === '1'){
            this.editableTabsDb.forEach(item => {
              if(item.title === this.form.strategy){
                _flag = true
                return this.$message.warning('该策略名称已存在,请更换')
              }
            })
            if(!_flag){
              this.addDbForm()
              this.open = false
            }
          }else{
            this.editableTabsXb.forEach(item => {
              if(item.title === this.form.strategy){
                _flag = true
                return this.$message.warning('该策略名称已存在,请更换')
              }
            })
            if(!_flag){
              this.addXbForm()
              this.open = false
            }
          }
        }
      })
    },
    // 策略名称取消
    onStrategyCancel(){
      this.resetStrategyForm()
      this.clearValidate()
      this.open = false
    },
    // 点击添加策略
    addTab() {
      this.resetStrategyForm()
      this.clearValidate()
      if(this.tenantId === '0' && this.editableTabsDb.length === 1 && this.warnTargetType === '1'){
        this.$message.warning('只能创建一个通用策略！')
      }else if(this.tenantId === '0' && this.editableTabsXb.length === 1 && this.warnTargetType === '2'){
        this.$message.warning('只能创建一个通用策略！')
      }else if(this.tenantId === '0' && this.editableTabsXb.length === 0 && this.warnTargetType === '2'){
        this.open = false
        this.form.strategy = '通用'
        this.addXbForm()
      } else if(this.tenantId === '0' && this.editableTabsDb.length === 0 && this.warnTargetType === '1'){
        this.open = false
        this.form.strategy = '通用'
        this.addDbForm()
      }else{
        this.open = true
      }
    },
    // 动态新增表单
    addDbForm() {
      const newId = this.editableTabsDb.length
      if (newId > 5) {
        return this.$message.warning("最多只能有五个报警策略")
      }
      const newForm = JSON.parse(JSON.stringify(this.formDb));
      // 创建新的表单时，给所属客户赋值
      newForm.fields.forEach(item => {
        if(item.label === '所属客户'){
          item.value = this.tenantId
        }
      })
      if(this.tenantId === '0' && this.editableTabsDb.length === 0){
        this.editableTabsDb.push({
          title: `通用`,
          name: `通用`,
          form: newForm,
          newStrategy: true,
          inputFlag: false,
          isNew: true, //是否为新建的表单
        });
      }else{
        this.editableTabsDb.push({
          title: this.form.strategy,
          name: this.form.strategy,
          form: newForm,
          newStrategy: true,
          inputFlag: false,
          isNew: true, //是否为新建的表单
        });
      }
      this.editableTabsValueDb = this.form.strategy
    },
    // 动态新增表单
    addXbForm() {
      const newId = this.editableTabsXb.length;
      if (newId > 5) {
        return this.$message.warning("最多只能有五个报警策略")
      }
      const newForm = JSON.parse(JSON.stringify(this.formXb));
      newForm.fields.forEach(item => {
        if(item.label === '所属客户'){
          item.value = this.tenantId
        }
      })
      if(this.tenantId === '0' && this.editableTabsXb.length === 0){
        this.editableTabsXb.push({
          title: `通用`,
          name: `通用`,
          form: newForm,
          newStrategy: true,
          inputFlag: false,
          isNew: true,
        });
        this.editableTabsValueXb = `通用`;
      }else{
        this.editableTabsXb.push({
          title: this.form.strategy,
          name: this.form.strategy,
          form: newForm,
          newStrategy: true,
          inputFlag: false,
          isNew: true,
        });
      }
      this.editableTabsValueXb = this.form.strategy
    },
    // 策略删除
    removeTab(targetName) {
      if(this.warnTargetType === '1') {
        let tabs = this.editableTabsDb;
        let activeName = this.editableTabsValueDb;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName && tab.isNew) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                // 如果是新增确还没点确定的可以×掉
                activeName = nextTab.name
                this.editableTabsValueDb = activeName;
                this.editableTabsDb = tabs.filter(tab => tab.name !== targetName);
              }else if(tab.isNew){
                this.editableTabsValueDb = activeName;
                this.editableTabsDb = tabs.filter(tab => tab.name !== targetName);
              }
            }
          });
        }
      }else{
        let tabs = this.editableTabsXb;
        let activeName = this.editableTabsValueXb;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName && tab.isNew) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
                this.editableTabsValueXb = activeName;
                this.editableTabsXb = tabs.filter(tab => tab.name !== targetName);
              }else if(tab.isNew){
                this.editableTabsValueXb = activeName;
                this.editableTabsXb = tabs.filter(tab => tab.name !== targetName);
              }
            }
          });
        }
      }
    },
    // 当所属客户下拉框改变时触发
    tenantIdChange(e) {
      this.resetForm()
      if(e == null || e === ''){
        e = '0'
      }
      this.getUsageRange(e)
    },
    // 当批量修改报警策略弹框中的用户下拉发生改变时，获取策略配置
    handleTenantIdChange(e){
      this.getStrategyList(e)
    },
    // 获取个用户的用量区间配置strategy列表
    getStrategyList(tenantId){
      this.strategyList = []
      getUsageRange(tenantId, this.warnTargetType).then(response =>{
        if(response.code === 200 && response.data){
          response.data.forEach(item => {
            let obj = {
              label: item.strategyName,
              value: item.strategy,
            }
            this.strategyList.push(obj)
          })
        }
      })
    },
    // 获取用量区间参数接口
    getUsageRange(tenantId) {
      this.dataDb = []
      this.dataXb = []
      // 判断是否是具体水司 如果是就先获取通用配置
      getUsageRange(tenantId, this.warnTargetType).then(response => {
        if (response.code === 200 && response.data) {
          // 整理出大用户表和户表数据
          for (let i = 0; i < response.data.length; i++) {
            if (response.data[i].warnTargetType === '1') {
              this.dataDb.push(response.data[i])
            } else {
              this.dataXb.push(response.data[i])
            }
          }
          // 判断当前是大用户表还是户表报警tab 然后对数据处理
          if (this.warnTargetType === '1') {
            this.editableTabsDb = []
            for (let i = 0; i < this.dataDb.length; i++) {
              if (this.dataDb.length > 0) {
                const newForm = JSON.parse(JSON.stringify(this.formDb));
                let editableTabsXbItem = {
                  name: this.dataDb[i].strategyName,
                  title: this.dataDb[i].strategyName,
                  form: newForm,
                  newStrategy: false,
                  inputFlag: false,
                  isNew: false,
                }
                this.editableTabsValueDb = this.dataDb[i].strategyName;
                this.editableTabsDb.push(editableTabsXbItem);
              }
            }
            this.handleData(this.dataDb, this.editableTabsDb, this.warnTargetType)
          } else {
            this.editableTabsXb = []
            for (let i = 0; i < this.dataXb.length; i++) {
              if (this.dataXb.length > 0) {
                const newForm = JSON.parse(JSON.stringify(this.formXb));
                let editableTabsXbItem = {
                  name: this.dataXb[i].strategyName,
                  title: this.dataXb[i].strategyName,
                  form: newForm,
                  newStrategy: false,
                  inputFlag: false,
                  isNew: false,
                }
                this.editableTabsValueXb = this.dataXb[i].strategyName;
                this.editableTabsXb.push(editableTabsXbItem)
              }
            }
            this.handleData(this.dataXb, this.editableTabsXb, this.warnTargetType)
          }
        }
      })
    },
    // 处理数据
    handleData(_data, tabData, warnTargetType) {
      for (let i = 0; i < _data.length; i++) {
        for (let j = 0; j < tabData[i].form.fields.length; j++) {
          for (let k = 0; k < _data[i].data.length; k++) {
            if (tabData[i].form.fields[j].dictValue !== '' && tabData[i].form.fields[j].dictValue === _data[i].data[k].warnType) {
              tabData[i].form.fields[j].value = _data[i].data[k].value // 获取报警参数对镜的纸
              tabData[i].form.fields[j].enabled = _data[i].data[k].enabled //是否开启
            }
          }
          if (tabData[i].form.fields[j].label === '所属客户') {
            tabData[i].form.fields[j].value = _data[i].tenantId
          } else if (tabData[i].form.fields[j].label === '夜间小流时间段' && warnTargetType === '1') {
            if (_data[i].nightFlowBeginTime != null && _data[i].nightFlowEndTime != null) {
              tabData[i].form.fields[j].value = [_data[i].nightFlowBeginTime, _data[i].nightFlowEndTime]
            } else {
              tabData[i].form.fields[j].value = null
            }
          }else if(tabData[i].form.fields[j].label === 'strategy'){
            tabData[i].form.fields[j].value = _data[i].strategy
          }
        }
      }
    },
    // 提交表单
    // index:区分大小表类型 name：tabs名字 newStrategy: 判断是新建还是修改 form： form表单
    onSubmit(title, newStrategy, strategyIndex, form) {
      // const formRef = this.$refs['formDbRef' + strategyIndex];
      let data = []
      let params = {}
      // 遍历表单数据 处理成接口参数需要的格式
      if(form.fields.length > 0){
        form.fields.forEach(item => {
          if (item.label === '所属客户') {
            params.tenantId = item.value
          } else if (item.label === '夜间小流时间段' && this.warnTargetType === '1') {
            if(item.value !== null){
              params.nightFlowBeginTime = item.value[0]
              params.nightFlowEndTime = item.value[1]
            }else{
              params.nightFlowBeginTime = null
              params.nightFlowEndTime = null
            }
          } else if(item.label === 'strategy' && !newStrategy) {
            params.strategy = item.value
          } else if(item.dictValue !== ''){
            // if(item.value != null){
              let obj = {
                warnType: item.dictValue,
                value: item.value,
                enabled: item.enabled,
              }
              data.push(obj)
            // }
          }
        })
        params.data = data
        params.warnTargetType = this.warnTargetType
        params.strategyName = title
      }
      this.$refs[this.warnTargetType === '1' ? `formDbRef${strategyIndex}` : `formXbRef${strategyIndex}`][0].validate((valid) => {
        if (valid) {
          usageRange(params).then(response => {
            if (response.code === 200) {
              this.$message.success(response.msg)
              // this.$message.success(newStrategy ? '创建成功' : '设置成功')
            }
            this.getUsageRange(this.tenantId)
          })
        }
      })
    },
    // 删除报警策略
    handleDelete(index, name, form) {
      let params = {}
      form.fields.forEach(item => {
        if(item.label === '所属客户'){
          params.tenantId = item.value
        }else if(item.label === 'strategy'){
          params.strategy = item.value
        }
        params.warnTargetType = index
      })
      this.$modal.confirm('是否确认删除数据项？').then(function () {
        return deleteUsageRange(params);
      }).then(() => {
        this.getUsageRange(this.tenantId)
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 获取报警类型
    getAlarmType() {
      getDicts('warn_param_type').then(res => {
        if (res.code === 200) {
          this.alarmTypeList = res.data
          this.createForm(this.alarmTypeList)
        }
      })
    },
    // 自动生成表单
    async createForm(alarmList) {
      let temp_fieldDb = [{
        dictValue: '',
        label: '所属客户',
        placeholder: '请选择所属客户',
        value: null,
        remark: null,
      }, {
        dictValue: '',
        label: '夜间小流时间段',
        placeholder: '请选择夜间小流时间段',
        value: null,
        rules: {required: true, message: "请选择时间", trigger: "blur"},
        remark: null,
      }, {
        dictValue: '',
        label: 'strategy',
        placeholder: '请输入strategy',
        value: null,
        rules: {required: false, message: "请输入strategy", trigger: "blur"},
        remark: null,
      }]
      let temp_fieldXb = [{
        dictValue: '',
        label: '所属客户',
        placeholder: '请选择所属客户',
        value: null,
        remark: null,
      }, {
        dictValue: '',
        label: 'strategy',
        placeholder: '请输入strategy',
        value: null,
        rules: {required: false, message: "请输入strategy", trigger: "blur"},
        remark: null,
      }]
      // let list_ = []
      // temp_fieldDb.push(...JSON.parse(JSON.stringify(list_)))
      // temp_fieldXb.push(...JSON.parse(JSON.stringify(list_)))
      alarmList.forEach(item => {
        if (item.remark.substr(0, 1) === 'D') {
          let obj = {
            dictValue: item.dictValue,
            label: item.dictLabel,
            placeholder: '请输入' + item.dictLabel,
            remark: '描述：' + item.remark.substr(1, item.remark.length - 1),
            // rules: {required: true, message: item.dictLabel + "不能为空", trigger: "blur", type: 'number'},
            rules: [{required: true, message: item.dictLabel + "不能为空", trigger: "blur"}],
            value: null,
            enabled: null,
          }
          temp_fieldDb.push(obj)
        } else if (item.remark.substr(0, 1) === 'X') {
          let obj = {
            dictValue: item.dictValue,
            label: item.dictLabel,
            placeholder: '请输入' + item.dictLabel,
            remark: '描述：' + item.remark.substr(1, item.remark.length - 1),
            rules: [{required: true, message: item.dictLabel + "不能为空", trigger: "blur"}],
            value: null,
            enabled: null,
          }
          temp_fieldXb.push(obj)
        }
      })
      this.formDb.fields = temp_fieldDb
      this.formXb.fields = temp_fieldXb
      await this.getUsageRange(this.tenantId)
    },
    // 切换 户表用量区间设置 大用户表用量区间设置
    handleTabClick(e) {
      this.warnTargetType = e._props.name
      this.queryParams.pageNum = 1
      this.isSelectAll = true
      if((this.warnTargetType === '2' && !this.isSelectAll) || (this.warnTargetType === '1' && !this.isSelectAll)){
        this.confirmRefreshData()
      }else if((this.warnTargetType === '2' && !this.openStrategy) || (this.warnTargetType === '1' && !this.openStrategy)){
        this.getUsageRange(this.tenantId)
      }
      // this.getUsageRange(this.tenantId)
    },
    // 重置表单
    resetForm() {
      // 1大表 2小表
      if (this.warnTargetType === '1') {
        this.formDb.fields.forEach(item => {
          item.value = null
        })
      } else if (this.warnTargetType === '2') {
        this.formXb.fields.forEach(item => {
          item.value = null
        })
      }
    },
    // 重置策略名称表单
    resetStrategyForm(){
      this.form = {
        strategy: null
      }
    },
    // 获取所有客户
    getDeptList() {
      deptList().then(response => {
        this.deptOption = response.data
        if(this.systemFlag === 0){
          this.deptOption.push({deptName: '通用', tenantId: '0'})
        }
      })
    },
  }
}
</script>
<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  background: white;
  padding: 10px 20px;
  position: relative;
  overflow: auto;
}

.box {
  //padding: 20px 10px;
  border: 1px solid #e8e8e8;
  border-radius: 5px;
  width: 60%;
  margin: 10px auto 0 auto;
}

.box-title {
  font-size: 16px;
  padding: 12px 20px;
  color: white;
  background: rgba(0, 75, 150, 0.8);
}

.box-form {
  //margin-top: 10px;
  overflow: auto;
  padding-bottom: 20px;

  span {
    color: rgba(33, 132, 166, 0.6);
    font-size: 13px;
    padding-left: 10px;
  }
  //
  //::v-deep .el-tabs__content {
  //  //min-height: 580px !important;
  //  max-height: 600px !important;
  //  overflow: auto;
  //}
}

.mb20 {
  margin-bottom: 20px;
}

.pt20 {
  padding-top: 30px;
}

.mb40 {
  margin-bottom: 40px;
}

.btn-box {
  text-align: center;
}
::v-deep .el-transfer-panel{
  width: 610px;
}
::v-deep .el-transfer-panel__body {
  min-height: 550px;
  height: auto;
}
//::v-deep .el-transfer-panel__footer{
//  //height: 40px;
//  overflow-x: auto;
//}
//::v-deep .el-checkbox-group{
//  height: 500px;
//}
::v-deep .el-transfer-panel .el-transfer-panel__footer{
  height: 50px;
}
</style>
